<?php

namespace App\Services\RegisterNewUser;

use App\Models\User;
use App\Models\RegisterPhone;
use App\Services\UserInviteInfo\UserInviteInfo;
use App\Services\UserInviteInfo\MakeUserAvatar;
use Rainsens\Dinglog\Facades\Dinglog;

class RegisterNewUser
{
	protected $name;
	
	protected $phone;
	
	protected $password;

	
	/**
	 * @var User
	 */
	protected $inviter = null;
	
	public function __construct($name, $phone, $password, $inviteCode = null)
	{
		$this->name = $name;
		$this->phone = $phone;
		$this->password = $password;
		$this->isRegister = RegisterPhone::query()->where("phone",$this->phone)->first();
		$this->setInviter($inviteCode);
	}
	
	protected function setInviter($inviteCode)
	{
		if (! $inviteCode) return;
		$this->inviter = app(UserInviteInfo::class)->userFromInviteCode($inviteCode);
	}
	
	protected function registerByInviter()
	{
		$result =  $this->inviter->children()->create([
			'grade' => 'normal',
			'name' => $this->name,
			'phone' => $this->phone,
			'password' => bcrypt($this->password),
			'is_show_support' => $this->isRegister  ? 1 : 0,
			'contact_phone' => !empty(request('is_allowed')) ? $this->phone : '',
		]);

		if(!$this->isRegister){

			RegisterPhone::create(['phone'=>$this->phone]);
		}
		
		
		$result->addTeamRelationUser();

		$avatar = app(MakeUserAvatar::class, [
			'name' => $this->name,
			'id' => $result->id,
		])->make();

		User::find($result->id)->update(["avatar"=>$avatar]);

		return $result;
	}
	
	protected function registerBySelf()
	{
		
		$result =  User::create([
			'grade' => 'normal',
			'name' => $this->name,
			'phone' => $this->phone,
			'password' => bcrypt($this->password),
			'is_show_support' => $this->isRegister  ? 1 : 0,
			'contact_phone' => !empty(request('is_allowed')) ? $this->phone : '',
		]);

		if(!$this->isRegister){

			RegisterPhone::create(['phone'=>$this->phone]);
		}
		//'avatar' => $avatar,

		$avatar = app(MakeUserAvatar::class, [
			'name' => $this->name,
			'id' => $result->id,
		])->make();

		User::find($result->id)->update(["avatar"=>$avatar]);

		return $result;
	}
	
	public function register()
	{
		if ($this->inviter) {
			return $this->registerByInviter();
		}
		
		return $this->registerBySelf();
	}
}
